<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>自定义查询添加编辑</title>
    <link rel="stylesheet" href="${ctx}/css/form.css">
    <#include "/pubHeadStyle.html">
</head>
<body>
<form class="layui-form" lay-filter="formData" id="formData" style="background: #fff;">
    <div class="layui-btn-container" style="position: absolute;bottom: 0;left:42%">
        <a class="layui-btn" lay-submit lay-filter="save">保存</a>
        <a class="layui-btn layui-btn-danger cancel">取消</a>
    </div>
    <div class="formQuerySearch">
        <div class="layui-form-item" style="padding-top:14px;">
            <div class="layui-inline" style="margin-right: 0">
                <label class="layui-form-label" style="width: 89px;">查询名称: </label>
                <div class="layui-input-inline">
                    <input type="text" name="name" id="name" style="width:200px" class="layui-input"
                           autocomplete="off" onblur="autoGetName(this)" maxlength="12"/>
                </div>
                <textarea id="textarea" style="display: none"></textarea>
                <div style="float: left;margin-left: 58px;">
                    <label class="layui-form-label">查询别名:<span style="color:red;">*</span> </label>
                    <div class="layui-input-inline">
                        <input type="text" name="alias" style="width: 200px" id="alias" class="layui-input"
                               lay-verify="required" maxlength="12"/>
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item" id="editHidden">
            <div class="layui-inline" style="margin-right: 0">
                <label class="layui-form-label" style="width: 89px;">数据源: </label>
                <div class="" style="float:left;width: 200px;">
                    <select name="dsalias" id="dataSource">
                        <option value="LOCAL">本地数据源</option>
                    </select>
                </div>
                <div style="float: left;margin-left: 35px; position: relative">
                    <label class="layui-form-label" style="width: 100px">查询表(视图): </label>
                    <div style="float: left;width: 203px;" class="tableSelect">
                        <select name="isTable" id="isTable" style="">
                            <option value="1">表</option>
                            <option value="0">视图</option>
                        </select>
                        <input class="layui-input" id="objectName" style="width: 116px;">
                    </div>
                    <div class="election">
                        <button type="button" class="layui-btn layui-btn-sm choice">
                            <i class="layui-icon layui-icon-search"></i>
                        </button>
                    </div>
                </div>
            </div>

        </div>
    </div>
</form>

<div class="layui-form-item">
    <div class="layui-inline">
        <label class="layui-form-label" style="width: 89px;">查询字段设置: </label>
        <div class="layui-input-block" style="margin-left:118px">
            <button type="button" class="layui-btn layui-btn-sm" style="display:none;margin:5px;margin-left:0" id="setCol">设置列</button>
            <script type="text/html" id="headerToolBar">
                <button type="button" class="layui-btn layui-btn-sm" style="margin:5px;margin-left:0"
                        lay-event="SetCol">设置列
                </button>
            </script>
            <div style="width: 570px">
                <table id="tableList" lay-filter="tableList"></table>
            </div>
        </div>
    </div>
</div>
<script src="${ctx}/extends/jquery.min.js" type="text/javascript"></script>
<script>
    var setter;
    var formQueryId = '${formQueryId}';
    var alias = '${alias}';
    var numJudge;
    var commons;
    layui.config({
        base: serverPath.formPath + staticPath.formPath //静态资源所在路径
    }).extend({
        index: 'index' //主入口模块
    }).use(['index', 'form', 'jquery', 'layer', 'table','totalFilter','commons'], function () {
        var form = layui.form, layer = layui.layer, table = layui.table;
        setter = layui.setter;
        var $ = layui.$;
        commons = layui.commons;
        form.render();

        if(formQueryId===""){//添加
            //加载空表格
            var result = new Array();
            loadTable(result,'请根据数据源来查询表并且选择其中一张表');
            //获取全部数据源
            $.ajax({
                url: serverPath.systemPath + setter.sysLinkPath +'dataSource/listAll',
                type: "post",
                dataType: 'json',
                success: function (result) {
                    if(result.data.length>0){
                        var text = "";
                        for (var i = 0; i < result.data.length; i++) {
                            text += "<option value='"+result.data[i]["alias"]+"'>"+result.data[i]["alias"]+"</option>"
                        }
                        $("#dataSource").append(text);
                        form.render('select');
                    }
                }
            });
        }else{//编辑
            $("#setCol").attr("style","margin:5px;margin-left:0");
            $("#editHidden").attr("style","display:none");
            $("#tableList").attr("style","display:none");
            if(numJudge===undefined){
                $.ajax({
                    url: serverPath.formPath + setter.formLinkPath +"formQuery/queryObj",
                    dataType: 'json',
                    type: "post",
                    data: {"alias": alias},
                    success: function (result) {
                        if(commons._filterRecord(result)){
                            $("#name").val(result.data.name);
                            $("#alias").val(result.data.alias);
                            $("#textarea").text(JSON.stringify({"conditionfield":JSON.parse(result.data.conditionfield),"resultfield":JSON.parse(result.data.resultfield),"sortfield":JSON.parse(result.data.sortfield)}));
                        }
                    }
                });
            }
        }

        //查询表或视图
        $('.choice').on('click', function () {
            var dsName = $("#dataSource option:selected").val();//数据源别名
            var isTable = $("#isTable option:selected").val();//是表或视图
            var objectName = $("#objectName").val();//表名或视图名
            $.ajax({
                url: serverPath.formPath + setter.formLinkPath + 'formQuery/getByDsObjectName',
                type: "post",
                dataType: 'json',
                data: {"dsName": dsName, "isTable": isTable, "objectName": objectName},
                success: function (data) {
                    if (commons._filterRecord(data)) {
                        var result = new Array();
                        $.each(data.data, function (i) {
                            if(i==="tables"){
                                $.each(data.data.tables, function (a) {
                                    result.push({"queryName": a})//+"("+data.data.tables[a]+")"
                                });
                            }else{
                                $.each(data.data.views, function (b) {
                                    result.push({"queryName": data.data.views[b]})
                                });
                            }
                        });
                        loadTable(result,'无数据！');
                    } else {
                        layer.alert(data.msg);
                    }
                }
            })
        });

        //编辑页面下 设置列按钮
        $("#setCol").click(function() {
            parent.layer.open({
                type: 2,
                title: "设置列",
                shade: 0.3,
                area: ['1100px', '600px'],
                content: serverPath.formPath + setter.formLinkPath + "formQuery/view/setCol?formQueryId=${formQueryId}"
            });
        });

        //将子页面的数据添加到隐藏的textarea
        parent.window.addSetCol=function(conditionfield,resultfield,sortfield,num){
            $("#textarea").text(JSON.stringify({"conditionfield":conditionfield,"resultfield":resultfield,"sortfield":sortfield}));
            numJudge = num;
        };
        //编辑时获取父页面隐藏的textarea
        parent.window.getArea=function(){
            return $("#textarea").text();
        };
        function loadTable(result,msg) {
            table.render({
                elem: '#tableList'
                , data: result
                , page: false
                ,limit: 10000
                , height: 'full-170'
                , toolbar: "#headerToolBar"
                , defaultToolbar: []
                , text: {
                    none: msg //默认：无数据
                }
                , cols: [[
                    {type: 'radio'}
                    , {field: 'queryName', title: '名称', width: 516, align: 'center'}
                ]]
            });
        }

        //工具监听
        var objectName;
        table.on('toolbar(tableList)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id);
            var data = checkStatus.data; //获取选中行数据
            switch (obj.event) {//设置列
                case 'SetCol':
                    if(data == ""){
                        layer.alert("请先选择数据库表")
                    }else{
                        objectName = data[0]["queryName"];//所选的表名或视图名
                        var dsName = $("#dataSource option:selected").val();//数据源别名
                        var isTable = $("#isTable option:selected").val();//是表或视图
                        parent.layer.open({
                            type: 2,
                            title: "设置列",
                            shade: 0.3,
                            area: ['1100px', '600px'],
                            content: serverPath.formPath + setter.formLinkPath + "formQuery/view/setCol?dsName="+dsName+"&isTable="+isTable+"&objectName="+objectName
                        });
                    }
                    break;
            }
        });

        //关闭弹窗
        $(".cancel").on("click", function () {
            parent.layer.close(parent.layer.getFrameIndex(window.name));
        });

        //保存方法
        form.on('submit(save)', function (data) {
            if(formQueryId===""){
                data.field.dsname = $("#dataSource option:selected").text();//数据源名称
                data.field.objName = objectName;//表名或视图名
            }
            if($("#textarea").text()===""){
                layer.alert("请在设置列中选择返回字段!");
                return false;
            }
            var allField = JSON.parse($("#textarea").text());
            data.field.conditionfield = JSON.stringify(allField.conditionfield);
            data.field.resultfield = JSON.stringify(allField.resultfield);
            if(allField.resultfield.length===0){
                layer.alert("请在设置列中选择返回字段!");
                return false;
            }
            data.field.sortfield = JSON.stringify(allField.sortfield);
            data.field.id = formQueryId;

            $.ajax({
                url: serverPath.formPath + setter.formLinkPath + "formQuery/add",
                type: "POST",
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify(data.field),
                success: function (result) {
                    if (commons._filterRecord(result)) {
                        layer.alert(result.msg,{skin: 'btn-class'}, function () {
                            parent.layui.table.reload('formQuery', {
                                page: {
                                    curr: 1
                                }
                            });
                            parent.layui.totalFilter.init('formQuery');
                            commons._bulletWindow(parent.layer.getFrameIndex(window.name));
                        });
                    } else {
                        layer.alert(result.msg,{skin: 'btn-class'});
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    layer.alert("保存失败！" + XMLHttpRequest.status);
                }
            });
            return false;
        });
    });
    /**
     * 根据字段描述生成字段名
     * @param inputObj
     */
    function autoGetName(inputObj) {
        var tableDesc = $(inputObj).val();
        if ($.trim(tableDesc).length < 1) return;
        $.ajax({
            url: serverPath.formPath + setter.formLinkPath +"table/getFieldKey",
            dataType: 'json',
            data: ({fieldDesc: tableDesc}),
            success: function (obj) {
                if (commons._filterRecord(obj)) {
                    $("#alias").val(obj.data);
                }
            }
        });
    }
</script>
<style>
    body {
        background: #fff;
    }
    .layui-form-select .layui-input {
        width: 200px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
    .layui-table-tool {
        background: #fff;
        margin-top:-20px;
        padding-left: 0;
    }
    .layui-table-tool-temp {
        padding-top: 7px;
    }
    .layui-table-body{
        overflow-x: hidden;
    }
    .layui-table-box{
        border: 1px solid #f2f2f2;
    }
    .layui-table-view{
        border:none;
    }
    .tableSelect .layui-unselect{
        width: 80px;
        float: left;
        margin-right:5px;
    }
    .tableSelect .layui-form-select .layui-input{
        width: 80px;
    }
    .tableSelect .layui-form-select dl{
        width: 80px;
    }
</style>
</body>
</html>
